<template>
  <div class="hm-cover">
    <!-- 图片按钮 -->
    <div class="btn_img" @click="openDialog">
      <img :src="showImage" />
    </div>
    <el-dialog title="上传封面" :visible.sync="dialogVisible" width="960px">
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="素材库" name="picture">
          <el-radio-group @change="change" v-model="collect">
            <el-radio-button :label="false">全部</el-radio-button>
            <el-radio-button :label="true">收藏</el-radio-button>
          </el-radio-group>

          <el-row :gutter="10">
            <el-col
              @click.native="selected(item.url)"
              :span="6"
              v-for="item in pictures"
              :key="item.id"
            >
              <el-image
                :class="{ selected: item.url === selectedImage}"
                :src="item.url"
                style="width: 100%; height: 140px"
                fit="cover"
              ></el-image>
            </el-col>
          </el-row>
           <el-pagination
            background
            @current-change="handleCurrentChange"
            :current-page="page"
            :page-size="per_page"
            layout="total, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="上传图片" name="upload">
          <el-upload
            class="avatar-uploader"
            action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
            :headers="headers"
            name="image"
            :show-file-list="false"
            :on-success="success"
            :before-upload="beforeUpload"
            :on-error="error"
          >
            <img class="avatar" :src="uploadImage" v-if="uploadImage" alt="">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-tab-pane>
      </el-tabs>
      <!-- footer插槽用于存放按钮 -->
      <template v-slot:footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { GetToken } from '@/utils/storage'
import { getPictureList } from '@/api/pictures'
import img from '@/assets/default.png'
/*
  如果网络图片，没有问题
  如果是本地图片
    1. 直接在模板中写图片地址，没问题，vue处理模板的时候会处理图片
    2. 需要引入本地图片，且把本地图片的地址写到data中，vue不会处理，解决方案：显示的导入这张图片
*/
export default {
  props: ['value'],
  data () {
    return {
      dialogVisible: false,
      activeName: 'picture',
      collect: false,
      pictures: [],
      page: 1,
      per_page: 8,
      total: 0,
      selectedImage: '',
      uploadImage: '',
      // 显示的图片地址
      showImage: this.value || img,
      headers: {
        Authorization: 'Bearer ' + GetToken()
      }
    }
  },
  watch: {
    value () {
      this.showImage = this.value || img
    }
  },
  methods: {
    openDialog () {
      this.dialogVisible = true
      this.getPictures()
    },
    async getPictures () {
      const res = await getPictureList({
        page: this.page,
        per_page: this.per_page,
        collect: this.collect
      })
      const { results, total_count } = res.data.data
      this.pictures = results
      this.total = total_count
    },
    handleCurrentChange (val) {
      this.page = val
      this.getPictures()
    },
    selected (url, e) {
      // 等价于在这打了一个段点
      // debugger
      if (this.selectedImage === url) {
        this.selectedImage = ''
      } else {
        this.selectedImage = url
      }
    },
    success (res) {
      console.log(res)
      this.uploadImage = res.data.url
    },
    beforeUpload (file) {
      if (file.size / 1024 / 1024 > 2) {
        this.$message.error('上传的文件不能超过2M')
        return false
      }
    },
    error () {
      this.$message.error('上传失败，稍后重试')
    },
    confirm () {
      // 判断当前tab栏是哪个
      if (this.activeName === 'picture') {
        // 素材
        // 判断是否选中了图片
        if (this.selectedImage) {
          this.showImage = this.selectedImage
        } else {
          return this.$message.error('请选择一张图片')
        }
      } else {
        // 上传
        if (this.uploadImage) {
          this.showImage = this.uploadImage
        } else {
          return this.$message.error('请上传图片')
        }
      }
      this.dialogVisible = false
      this.selectedImage = ''
      this.uploadImage = ''
      this.$emit('input', this.showImage)
    },
    change () {
      this.page = 1
      this.getPictures()
    }
  }
}
</script>

<style scoped lang='less'>
// 图片按钮
.btn_img {
  width: 150px;
  height: 150px;
  border: 1px dashed #ddd;
  img {
    width: 100%;
    height: 100%;
    display: block;
    object-fit: cover;
  }
}
.el-row {
  margin-top: 20px;
  .el-col {
    margin-top: 8px;
  }
}
.selected {
  position: relative;
  &::after {
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    // background-color: rgba(0, 0, 0, .5);
    // background-image: url('~@/assets/selected.png');
    // background-size: 80px 80px;
    // background-repeat: no-repeat;
    // background-position: center;
    background: rgba(0, 0, 0, .5) url('~@/assets/selected.png') no-repeat center / 80px 80px;
  }
}
</style>
